import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_notifier.dart';
import 'package:casdon/modules/login/data/api/login_api.dart';
import 'package:casdon/modules/login/data/api/valide_code_type.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/usecases/login_usecase.dart';
import 'package:casdon/modules/login/domain/usecases/send_emailCode_usecase.dart';
import 'package:casdon/modules/login/providers/login_code_provider.dart';
import 'package:casdon/modules/login/domain/usecases/send_sms_usecase.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';

class LoginCodeNotifier extends LoginNotifier<LoginCodeState> {
  LoginCodeStep step = LoginCodeStep.sendCode;

  Future<void> sendCode({
    SendCodeSource source = SendCodeSource.accountPage,
  }) async {
    step = LoginCodeStep.sendCode;
    if (CommonNetStatus.loading == state.status) {
      return;
    }

    if (false == state.agreed) {
      setFailure(msg: "请先同意用户协议");
      return;
    }

    if (null == state.account) {
      setFailure(msg: "请先输入账号");
      return;
    }

    state = state.copyWith(
      source: source,
      errorCode: null,
      code: null,
      message: null,
      status: CommonNetStatus.loading,
    );

    if (state.account!.isPhoneNum()) {
      _sendSmsCode(state.account!);
    } else if (state.account!.isEmail()) {
      _sendEmailCode(state.account!);
    } else {
      setFailure(msg: "账号格式不正确");
    }
  }

  void updateAccount(String value) {
    step = LoginCodeStep.sendCode;
    state = state.copyWith(
      account: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  void updateCode(String value) {
    step = LoginCodeStep.login;
    state = state.copyWith(
      code: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  void _sendSmsCode(String phone) async {
    try {
      SendSmsUsecase sendSmsUsecase = ref.read(sendSmsUsecaseProvider);
      final ret = await sendSmsUsecase.execute(phone, ValideCodeType.login);
      if (ret.success == true) {
        setSuccess("发送验证码成功");
      } else {
        setFailure(msg: ret.message ?? "发送验证码失败");
      }
    } catch (e) {
      setFailure(msg: getErrorMessage(e));
    }
  }

  void _sendEmailCode(String email) async {
    try {
      SendEmailcodeUsecase sendEmailcodeUsecase = ref.read(
        sendEmailcodeProvider,
      );
      final ret = await sendEmailcodeUsecase.execute(
        email,
        ValideCodeType.login,
      );
      if (ret == true) {
        setSuccess("发送验证码成功");
      } else {
        setFailure(msg: "发送验证码失败");
      }
    } catch (e) {
      setFailure(msg: getErrorMessage(e));
    }
  }

  // 验证码登录
  Future<void> login() async {
    state = state.copyWith(
      errorCode: null,
      message: null,
      status: CommonNetStatus.loading,
    );
    step = LoginCodeStep.login;
    var grantType = LoginGrantType.sms.name;
    // if (state.account!.isEmail()) {
    //   grantType = LoginGrantType.email.name;
    // }
    try {
      LoginUsecase loginUsecase = ref.read(loginUsecaseProvider);
      RequestLogin request = RequestLogin(
        grantType: grantType,
        phonenumber: state.account,
        smsCode: state.code,
      );
      final ret = await loginUsecase.execute(request);
      Log.i("验证码登录成功，token = ${ret.access_token}");

      final authStorage = ref.read(authStorageProvider.notifier);
      await authStorage.saveToken(ret.access_token);
      await ref.read(tuyaLoginProvider.notifier).login();
      final tuyaSuccess = ref.read(tuyaLoginStateProvider);
      if (!tuyaSuccess) {
        setFailure(msg: "登录失败，请稍后再试！");
        return;
      }

      setSuccess("登录成功");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "登录失败，请稍后再试！");
    }
  }

  @override
  LoginCodeState build() {
    ref.onDispose(() {
      Log.d("已经销毁：LoginCodeNotifier");
    });
    return LoginCodeState.initial();
  }
}
